package net.util;

import java.util.ArrayList;
import javax.swing.JOptionPane;
import net.Molecules;

public class ThrowableHandler 
{

	private ArrayList<Exception> ignoreExceptionList = new ArrayList<>(), 
			queriedExceptionList = new ArrayList<>();

	public static String stackTrace(Throwable t)
	{
		String S = "";

		for(StackTraceElement ste : t.getStackTrace())
		{
			S += ste.getClassName() + ": " + ste.getMethodName() + ", " + ste.getLineNumber() + "\n";
		}

		return S;
	}

	public void handleException(Exception e)
	{
		for(Exception e2 : ignoreExceptionList)
		{
			if (e.getClass() == e2.getClass() && BooleanUtil.argumentsAreNullOrEqual(e.getMessage(),e2.getMessage()))
			{
				return;
			}
		}

		int i = JOptionPane.showConfirmDialog(null, 
				"Exception occured: " 
						+ "\n"+ e.getClass().getName() 
						+ "\nInfo: " + (e.getLocalizedMessage() == null ? "unknown" : e.getLocalizedMessage())
						+ "\nCaused by: " + (e.getCause() == null ? "unknown" : e.getCause())
						+ "\nWould you like to abort execution?",
						"ERROR", JOptionPane.YES_NO_OPTION);

		if(i == JOptionPane.YES_OPTION)
		{
			Molecules.cleanUp();
			System.exit(0);
		}
		else if(i == JOptionPane.NO_OPTION)
		{
			i = JOptionPane.showConfirmDialog(null, 
					"Would you like this particular exception to be ignored for the duration of this execution?", 
					"Query", JOptionPane.YES_NO_OPTION);

			queriedExceptionList.add(e);

			if(i == JOptionPane.YES_OPTION)
			{
				ignoreExceptionList.add(e);
			}
		}
	}

	public void handleErrorAndExit(Error e)
	{
		JOptionPane.showMessageDialog(null,  
				"Java has encountered a serious error and needs to close.\n"
						+ e.getClass().getName() 
						+ "\nInfo: " + (e.getLocalizedMessage() == null ? "unknown" : e.getLocalizedMessage())
						+ "\nCaused by: " + (e.getCause() == null ? "unknown" : e.getCause()), 
						"ERROR", 0);
		Molecules.cleanUp();
		System.exit(1);
	}
}
